import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import router from 'umi/router';

import {
    Card,
    Row,
    Col,
    Modal,
    Button,
    message,
} from 'antd';
import { Form } from '@ant-design/compatible';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { QuestionCircleTwoTone } from '@ant-design/icons';
import PageHeader from '@/components/PageHeader';

import qs from 'qs';

import { addTab } from '@/utils/utils';

import BasicInfoElem from './components/BasicInfoElem';
import CabinetInfoElem from './components/CabinetInfoElem';

import '@ant-design/compatible/assets/index.css';

interface CabinetManageAddProps extends FormComponentProps {
    dispatch: Dispatch;
    location: { query: any };
    detailInfo: any;
    checkPerm: any;
}

interface CabinetManageAddState {
    hardwareVersion: string;
    layout: {
        left: number;
        right: number;
    };
    layoutInfo: any[];
    selectGarden: { id?: number; name?: string };
    selectAdmin: { id?: number; name?: string };
    reservationDialog: boolean;
    whiteListDialog: boolean;
}

@connect(({
    cabinetManagementAdd: { detailInfo },
    common: { checkPerm },
}: any) => ({
    detailInfo,
    checkPerm,
}))
class CabinetManageAddElem extends Component<CabinetManageAddProps, CabinetManageAddState> {
    state: CabinetManageAddState = {
        hardwareVersion: '1.0',
        layout: { left: 0, right: 0 },
        layoutInfo: [],
        selectGarden: {},
        selectAdmin: {},
        reservationDialog: false,
        whiteListDialog: false,
    };

    componentDidMount() {
        const {
            location: { query: { id } },
        } = this.props;
        if (id) this.fetchDetailInfo(id);

        this.fetchCheckPerm();
    }

    componentDidUpdate(props: any) {
        const {
            location: { query: { id } },
        } = this.props;
        if (id && id !== props.location.query.id) this.fetchDetailInfo(id);
    }

    componentWillUnmount() {
        this.fetchAction('clear');
    }

    fetchCheckPerm = () => {
        const Addparams = {
            name: 'delivery_whitelist_updata',
            oper: 'delivery_whitelist_updata',
            resource: 'conf:delivery_whitelist_conf',
        };

        this.fetchAction('common/fetchCheckPerm', Addparams);
    }


    fetchDetailInfo = (id: number) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'cabinetManagementAdd/fetch',
            payload: { id },
        });
    };

    changeHardwareVersion = (hardwareVersion: string) => {
        this.setState({ hardwareVersion }, () => this.createViceInfo());
    };

    changeLayout = (value: number, type: number) => {
        const { layout } = this.state;
        this.setState(
            {
                layout: {
                    ...layout,
                    left: type === 1 ? value : layout.left,
                    right: type === 2 ? value : layout.right,
                },
            }, () => {
                this.createViceInfo();
            },
        );
    };

    /**
     * 获取26因为字母数组
     */
    getAllChars = () => {
        const startChar = 65;
        const arr = [...new Array(26)];
        const allChars = arr.map((item: any, index: number) => String.fromCharCode(startChar + index));
        return allChars;
    };

    createViceInfo = () => {
        const { hardwareVersion, layout } = this.state;
        const allChars = this.getAllChars();
        if (hardwareVersion === '5.0' || hardwareVersion === '6.0' || hardwareVersion === '7.0') {
            const left = [...new Array(layout.left)].map((item: any, index: number) => ({
                isAdd: 1,
                slaveCode: index >= allChars.length ? `${allChars[Math.floor((index / allChars.length) - 1)]}${allChars[index % allChars.length]}` : allChars[index],
                slaveType: 1,
            }));

            const right = [...new Array(layout.right)].map((item: any, index: number) => {
                const slaveCode = layout.left + index + 1 >= allChars.length
                    ? `${allChars[Math.floor((layout.left + index + 1) / allChars.length) - 1]}${allChars[(layout.left + index + 1) % allChars.length]}`
                    : allChars[layout.left + index + 1];

                return {
                    isAdd: 1,
                    slaveCode,
                    slaveType: 1,
                };
            });

            this.setState({ layoutInfo: [...left, ...right] });
        }
    };

    checkPayMask = (tariffpkgId: number) => {
        // 检查付费方是否
        const { selectGarden } = this.state;
        const { form: { getFieldValue } } = this.props;
        const logisId = getFieldValue('logisId') || 0;

        const params = {
            tariffpkgId,
            logisId,
            gardenId: selectGarden.id || 0,
        };
        this.fetchAction('checkPayMask', params);
    };

    getChildData = (values: any, type: number) => {
        if (type === 1) this.setState({ selectGarden: values });
        if (type === 2) this.setState({ selectAdmin: values });
    };

    handleSubmit = () => {
        const { form: { validateFieldsAndScroll } } = this.props;
        validateFieldsAndScroll((errors, values) => {
            if (errors) return;

            const { longitude, latitude }: any = values;
            if (longitude.length > 16 || Number(longitude) < -180 || Number(longitude) > 180) {
                message.error('经度输入不正确');
                return;
            }

            if (latitude.length > 16 || Number(latitude) < -90 || Number(latitude) > 90) {
                message.error('纬度输入不正确');
                return;
            }

            const { code, bluetoothName } = values;
            if (bluetoothName && code !== bluetoothName) {
                message.error('蓝牙名称必须和柜体编号一致');
                return;
            }

            const { addr } = values;
            if (addr.length > 18) {
                message.error('短信地址字数不得大于18个');
                return;
            }

            const {
                layout_left = 0, layout_right = 0, mainType, vice = [], ...query
            } = values;
            const left = vice ? vice.slice(0, layout_left) : [];
            const right = vice ? vice.slice(layout_left, vice.length) : [];

            const main = mainType && mainType.key ? `${mainType.key},` : '';
            const leftContent = left.length > 0 ? `${left.join(',')},` : '';
            const slaveList = `${leftContent}${main}${right.join(',')}`;

            /**
                 * 筛选新增的副柜
                 */

            const { detailInfo } = this.props;
            const { cellInfo = [] } = detailInfo;

            const new_slaveList_arr = vice && vice.length > (cellInfo?.length || 0) ? vice[vice.length - 1] : '';
            const {
                selectGarden: { id: gardenId },
                selectAdmin: { id: managerUid },
            } = this.state;
            const params = {
                ...query,
                gardenId,
                managerUid,
                isDepositEnabled: Number(query.isDepositEnabled),
                isLetterEnabled: Number(query.isLetterEnabled),
                cabSendingEnabled: Number(query.cabSendingEnabled),
                payMaskStr: query.payMaskStr ? query.payMaskStr.join(',') : '',
                slaveList: detailInfo.id ? new_slaveList_arr : slaveList,
            };
            if (detailInfo.id) {
                params.letterCellMode = detailInfo.letterCellMode;
                params.id = detailInfo.id;
            } else {
                params.layout = `${layout_left}-${layout_right}`;
            }

            this.fetchAction('addOrupdateCab', params);
        });
    };

    fetchAction = (typeName: string, payload: any = {}) => {
        const { dispatch } = this.props;
        const type = typeName.indexOf('common') >= 0
            ? typeName : `cabinetManagementAdd/${typeName}`;
        dispatch({ type, payload });
    };

    handleBookingCourier = () => {
        const {
            detailInfo: {
                id, name, code, statusName,
            },
        } = this.props;
        const query = {
            id,
            name,
            code,
            statusName,
        };

        const { dispatch } = this.props;
        addTab(dispatch, {
            name: '配置预约快递员',
            url: `/basic/cabinetManagement/list/bookingCourier?${qs.stringify(query)}`,
        });
    }

    handleDeliveryWhiteList = () => {
        const { dispatch, detailInfo } = this.props;
        const query = {
            id: detailInfo.id,
            name: detailInfo.name,
            code: detailInfo.code,
            statusName: detailInfo.statusName,
        };

        addTab(dispatch, {
            name: '配置投递白名单',
            url: `/basic/cabinetManagement/list/deliveryWhiteList?${qs.stringify(query)}`,
        });
    }

    render() {
        const {
            hardwareVersion,
            layoutInfo,
            reservationDialog,
            whiteListDialog,
        } = this.state;

        const {
            form,
            detailInfo,
            checkPerm,
        } = this.props;

        return (
            <Fragment>
                <PageHeader />

                <Form
                    hideRequiredMark
                    className="tableListForm"
                    colon={false}
                >
                    <BasicInfoElem
                        forms={form}
                        changeHardwareVersion={this.changeHardwareVersion.bind(this)}
                        checkPayMask={this.checkPayMask.bind(this)}
                        getChildData={this.getChildData.bind(this)}
                    />

                    <Card bordered={false} title="功能配置">
                        <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                            {detailInfo.id && (
                                <Col md={8} sm={24}>
                                    <Form.Item label="预约快递员管理" colon={false}>
                                        <div style={{ display: 'flex', alignItems: 'center' }}>
                                            <Button
                                                type="primary"
                                                onClick={this.handleBookingCourier}
                                            >
                                                配置预约快递员
                                            </Button>
                                            <QuestionCircleTwoTone
                                                style={{ marginLeft: 8, fontSize: 18 }}
                                                onClick={() => this.setState({ reservationDialog: true })}
                                            />
                                        </div>
                                    </Form.Item>
                                </Col>
                            )}
                            {detailInfo.id && checkPerm.delivery_whitelist_updata && (
                                <Col md={8} sm={24}>
                                    <Form.Item label="投递白名单管理" colon={false}>
                                        <div style={{ display: 'flex', alignItems: 'center' }}>
                                            <Button
                                                type="primary"
                                                onClick={this.handleDeliveryWhiteList}
                                            >
                                                配置投递白名单
                                            </Button>
                                            <QuestionCircleTwoTone
                                                style={{ marginLeft: 8, fontSize: 18 }}
                                                onClick={() => this.setState({ whiteListDialog: true })}
                                            />
                                        </div>
                                    </Form.Item>
                                </Col>
                            )}
                        </Row>
                    </Card>

                    <CabinetInfoElem
                        forms={form}
                        hardwareVersion={hardwareVersion}
                        changeLayout={this.changeLayout.bind(this)}
                        getAllChars={this.getAllChars.bind(this)}
                        layoutInfo={layoutInfo}
                        fetchAction={this.fetchAction.bind(this)}
                    />

                    <Card bordered={false} style={{ marginTop: -20 }}>
                        <Button
                            type="primary"
                            onClick={this.handleSubmit}
                        >
                            保存
                        </Button>
                        <Button
                            ghost
                            type="primary"
                            className="marginL16"
                            onClick={() => router.goBack()}
                        >
                            取消
                        </Button>
                    </Card>
                </Form>

                <Modal
                    title="配置预约快递员说明"
                    visible={reservationDialog}
                    onCancel={() => this.setState({ reservationDialog: false })}
                    footer={[
                        <div key="ok" style={{ textAlign: 'center' }}>
                            <Button
                                type="primary"
                                onClick={() => this.setState({ reservationDialog: false })}
                            >
                                知道了
                            </Button>
                        </div>,
                    ]}
                >
                    <p style={{ textAlign: 'left' }}>
                        配置预约快递员功能是指运营人员可以添加预约指定柜体的快递员，
                        已添加的快递员可在邻宝快递员APP首页看到【柜体预约】功能入口，
                        未添加的快递员则不能在邻宝快递员APP首页看到【柜体预约】功能入口。
                    </p>
                </Modal>

                <Modal
                    title="配置投递白名单说明"
                    visible={whiteListDialog}
                    onCancel={() => this.setState({ whiteListDialog: false })}
                    footer={[
                        <div key="ok" style={{ textAlign: 'center' }}>
                            <Button
                                type="primary"
                                onClick={() => this.setState({ whiteListDialog: false })}
                            >
                                知道了
                            </Button>
                        </div>,
                    ]}
                >
                    <p style={{ textAlign: 'left' }}>
                        投递白名单配置功能是指运营人员可将指定快递员添加至白名单列表中，并为白名单外的快递员配置各类型格口最大可投递次数，白名单快递员可以正常使用该柜体的格口。
                    </p>
                </Modal>

            </Fragment>
        );
    }
}

export default Form.create<CabinetManageAddProps>()(CabinetManageAddElem);
